package com.example.book.controller;

import com.example.book.model.BookInfo;
import com.example.book.model.PageRequest;
import com.example.book.model.PageResult;
import com.example.book.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    @RequestMapping("/addBook")
    public String addBook(BookInfo bookInfo){
        log.info("接收到参数bookInfo: {}", bookInfo);
        //参数校验
        if(!StringUtils.hasLength(bookInfo.getBookName())
                || !StringUtils.hasLength(bookInfo.getAuthor())
                || !StringUtils.hasLength(bookInfo.getAuthor())
                || bookInfo.getCount() == null
                || bookInfo.getPrice() == null
                || !StringUtils.hasLength(bookInfo.getPublish())
                || bookInfo.getStatus()== null){
            return "输入参数不合法";
        }

        //添加图书
        try {
            Integer ret = bookService.insertBookInfo(bookInfo);
            if(ret > 0){
                return "";
            }
        }catch (Exception e){
            log.error("添加图书异常 e :", e);
        }

        return "添加失败";
    }

    /**
     * 显示图书列表
     */
    @RequestMapping("/getBookListByPage")
    public PageResult<BookInfo> getBookListByPage(PageRequest pageRequest){
        //参数校验
        if(pageRequest.getPageNum() < 0
                || pageRequest.getPageSize() < 0
                || pageRequest.getOffset() < 0){
            return null;
        }

        log.info("查询图书列表,请求参数pageRequest: {}", pageRequest);
        return bookService.getBookListByPage(pageRequest);
    }

}
